<?php

declare(strict_types=1);

namespace Modules\DataCheck\Http\Controllers;

use Catch\Exceptions\FailedException;
use Modules\DataCheck\Models\DcTaskTargetDownloadLog;
use Illuminate\Http\Request;

/**
 * @class DcTaskTargetDownloadLogController
 */
class DcTaskTargetDownloadLogController extends BaseController
{
    /**
     * @param DcTaskTargetDownloadLog $model
     */
    public function __construct(protected readonly DcTaskTargetDownloadLog $model)
    {

    }

    /**
     * 下载日志列表
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request): mixed
    {
        $taskId = $request->input('task_id');
        if (empty($taskId)) {
            throw new FailedException('task_id：任务ID不能为空');
        }

        // 使用CatchAdmin规范：通过setBeforeGetList处理关联关系，然后返回分页数据
        return $this->model->setBeforeGetList(function ($query) use ($taskId) {
            // 预加载任务信息（获取task_name）
            $query->with(['task' => function ($query) {
                $query->select('id', 'task_id', 'task_name', 'task_state');
            }]);
            
            // 预加载用户信息（获取username）
            $query->with(['downloadUser' => function ($query) {
                $query->select('id', 'username');
            }]);
            
            // 添加task_id过滤条件
            $query->where('task_id', $taskId);
            
            return $query;
        })->getList();
    }
}